package com.carwler.demo;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpPool {

	private static  final Logger LOGGER = LoggerFactory.getLogger( HttpPool.class );
	private static  HttpClient httpClient;
	private static PoolingHttpClientConnectionManager httpManage;

	static {
		httpManage = new PoolingHttpClientConnectionManager();
		httpManage.setMaxTotal( 200 );// 设置最大连接数
		httpManage.setDefaultMaxPerRoute( 20 );// 设置每个主机地址的并发数
		httpClient = HttpClients.custom().setConnectionManager( httpManage ).build();
	}
	
	public static String doGetRequest( String url ) throws Exception{
		return doGetRequest( url, null );
	}

	public static String doGetRequest( String url, String encode) throws Exception{
		if (StringUtils.isBlank( encode )) encode = "GBK";
		HttpGet httpGet = new HttpGet( url );
		String responseContent = null;
		try {
			HttpResponse response = httpClient.execute( httpGet );
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				responseContent = EntityUtils.toString( response.getEntity(), encode );
				LOGGER.debug( "GET请求成功,ResponseBody:{}", responseContent );
			}
		} catch (Exception e) {
			LOGGER.debug( "GET请求失败:{}", url, e );
		}finally {
			httpManage.closeIdleConnections( 1, TimeUnit.MINUTES );
		}
		return responseContent;
	}
	
	 /**
     * 下载文件
     * 
     * @param url 文件url
     * @param dest 目标目录
     * @throws Exception
     */
    public static void downloadFile(String url, File dest) throws Exception {
        LOGGER.info("下载文件，URL：" + url);
        HttpGet httpGet = new HttpGet(url);
        try {
        	HttpResponse response = httpClient.execute(httpGet);
            //FileUtils的写字节到文件中（目标目录，写入的内容）；IOUtils把（请求响应的内容）内容转换为字节
            FileUtils.writeByteArrayToFile(dest, IOUtils.toByteArray(response.getEntity().getContent()));
        } finally {
        	httpManage.closeIdleConnections( 1, TimeUnit.MINUTES );
        }
    }
}
